import baseURL from "./baseURL";

const requestInterceptor = function(config) {
	uni.showLoading({
		title: '加载中...',
		mask: true
	});
	return config;
}

const responseInterceptor = function(response) {
	uni.hideLoading();
	if (response.data.code === 401) {
		uni.showToast({
			title: '登录态已过期，请重新登录',
			icon: 'none'
		});
		setTimeout(() => {
			uni.reLaunch({
				url: "/pages/login/login"
			})
		}, 1000);
		return Promise.reject(response);
	} else if (response.data.code !== 200) {
		uni.showModal({
			title: '提示',
			content: response.data.message || '请求失败',
			showCancel: false
		});
		return Promise.reject(response);
	}
	return Promise.resolve(response.data);
}

function request(config) {
	config = requestInterceptor(config);

	return new Promise((resolve, reject) => {
		uni.request({
			url: baseURL + config.url,
			method: config.method,
			data: config.data,
			timeout: 5000,
			header: {
				Authorization: uni.getStorageSync("token") ? uni.getStorageSync("token") : ''
			},
			success(res) {
				// 执行响应拦截器
				responseInterceptor(res).then(data => {
					resolve(data);
				}).catch(error => {
					reject(error);
				});
			},
			fail(error) {
				uni.showToast({
					title: '网络请求失败，请稍后重试',
					icon: 'none'
				});
				reject(error);
			},
			complete() {
				uni.hideLoading();
			}
		});
	});
}

export default request;